package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {

    @Autowired
    IRoleService roleService;

    @RequestMapping("view")
    @RequiresPermissions(value = {"role:view","角色页面"},logical = Logical.OR)
    public String view() {
        return "role";
    }

    @RequestMapping("query")
    @ResponseBody
    @RequiresPermissions(value = {"role:query","角色列表"},logical = Logical.OR)
    public PageResult query(QueryObject qo) {
        return roleService.query(qo);
    }

    @RequestMapping("delete")
    @ResponseBody
    @RequiresPermissions(value = {"role:delete","角色删除"},logical = Logical.OR)
    public JsonResult delete(Long id) {
        try {
            roleService.deleteById(id);
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.mark("操作失败");
        }
    }

    @RequestMapping("selectPermissions")
    @ResponseBody
    public List<Permission> selectPermissions(Long roleId) {
        return roleService.selectPermissions(roleId);
    }

    @RequestMapping("getMenuIdByRoleId")
    @ResponseBody
    public List<Long> getMenuIdByRoleId(Long roleId) {
        return roleService.getMenuIdByRoleId(roleId);
    }

    @RequestMapping("selectAll")
    @ResponseBody
    public List<Role> selectAll() {
        return roleService.selectAll();
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"role:saveOrUpdate","角色新增/更改"},logical = Logical.OR)
    public JsonResult saveOrUpdate(Role role) {
        try {
            if (role.getId() != null) {
                roleService.updateByPrimaryKey(role);
            } else {
                roleService.insert(role);
            }
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.mark("保存失败");
        }
    }


}
